/*
 * @Author: yangzonglong
 * @Date: 2020-08-19 13:41:08
 * @version: v1.0.0
 * @Descripttion: 
 * @LastEditors: yangzonglong
 * @LastEditTime: 2023-09-18 14:11:44
 * @Auditor: 
 */
import { createBrowserHistory, History } from 'history';
import { Modal } from 'antd';
import { PACKAGE_NAME } from './automatic/package';
import { setRouteHistory } from './../utils/footprint/footprint';
import client from './../client';

type QuitInquiryProps = (() => boolean) | undefined;

const basename = process.env.NODE_ENV !== 'test' ? PACKAGE_NAME : '/';
let quitInquiry: QuitInquiryProps; // history push时需询问活动界面是否可切换

export type HistoryProps = History & {
  query: Record<string, any>;
  _prevPath?: string;
  _isFromBreadcrumb?: boolean;
};

export const __Sorter__ = '__Sorter__';

const _history = createBrowserHistory({ basename }) as HistoryProps;

const push = _history.push;
(window.top as any).childHistoryPush = push;

_history.push = (path: string, state?: unknown) => {

  // quitInquiry 询问当前界面是否可离开
  if (quitInquiry && !quitInquiry()) {
    const t = window.$app.t;

    Modal.confirm({
      title: t("confirmLeave"),
      content: t("confirmGoOther"),
      cancelText: t("noReturnEdit"),
      okText: t("goContinue"),
      onOk() {
        _history._isFromBreadcrumb = true;
        setQuitInquiry(() => true);
        push(path, state);
      },
    });
    return;
  }

  return push(path, state);
};

_history.listen(({location}) => {

  // 通知父框架路由切换
  if (client.historyPush) {
    const basename = `/app/${PACKAGE_NAME}${location.pathname}`;

    if (location.search) {
      client.historyPush(`${basename}${location.search}`);
    } else {
      client.historyPush(basename);
    }
  }

  if (_history._prevPath && typeof _history._prevPath === 'string') {
    const prevPath1 = _history._prevPath.split('/')?.[1];
    const pathname1 = location.pathname.split('/')?.[1];
    if (prevPath1 !== pathname1) {
      const list = `/${process.env.APP_ID}${_history._prevPath}`.split('/');
      list.forEach((ele: string, index: number) => {
        window.sessionStorage.removeItem('__' + list.slice(0, index + 1).join('/'));
      });
      delete (window as any)[__Sorter__];
    }
  }

  _history._prevPath = location.pathname;

  setRouteHistory(location.pathname, location.pathname + location.search);
});

export const setQuitInquiry = (_quitInquiry?: QuitInquiryProps) => {
  quitInquiry = _quitInquiry;
  client.setQuitInquiry?.(_quitInquiry); // 通知父框架
};

export default _history;